﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace JGSoft.U9CRTAPIEX.Public
{
    public class HttpHelper
    {
        public string URL { get; set; }
        public string Content { get; set; }
        public string Token { get; set; }
        public string Request(string postType = "POST")
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"请求地址:{URL}");
            var request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = postType;
            request.ContentType = "application/json";//ContentType
            if (!string.IsNullOrEmpty(Token))
                request.Headers.Add("token", Token);
            if (postType != "GET")
            {
                sb.AppendLine("请求参数:" + Content);
                byte[] byteData = Encoding.UTF8.GetBytes(Content);
                int length = byteData.Length;
                request.ContentLength = length;
                Stream writer = request.GetRequestStream();
                writer.Write(byteData, 0, length);
                writer.Close();
            }

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
                sb.AppendLine($"返回值:{responseString}");
                LogManager.WriteLog(sb.ToString(), "AllRequest");
                return responseString;
            }
            catch (Exception e)
            {
                sb.AppendLine($"{e.Message}\r\n{e.StackTrace}");
                LogManager.WriteLog(sb.ToString(), "All");
                throw new Exception(e.Message);
            }
        }
    }
}
